import hx.layout.AnchorLayoutData;
import hx.display.Label;
import hx.layout.AnchorLayout;
import hx.display.Quad;
import hx.events.Keyboard;
import hx.events.KeyboardEvent;
import hx.display.Stage;

class GameStage extends Stage {
	public var quad:Quad;

	override function onStageInit() {
		super.onStageInit();
		// 代码开始的地方...
		this.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown);
		this.addEventListener(KeyboardEvent.KEY_UP, onKeyUp);
		quad = new Quad(100, 100, 0xff0000);
		this.addChild(quad);

		this.layout = new AnchorLayout();
		var label = new Label("使用键盘ASWD移动红色方块");
		this.addChild(label);
		label.height = 60;
		label.horizontalAlign = CENTER;
		label.layoutData = new AnchorLayoutData(null, 0, 0, 0);
	}

	public var keys:Map<Int, Bool> = new Map<Int, Bool>();

	public function onKeyDown(e:KeyboardEvent) {
		switch e.keyCode {
			case Keyboard.A, Keyboard.D, Keyboard.W, Keyboard.S:
				keys.set(e.keyCode, true);
		}
	}

	public function onKeyUp(e:KeyboardEvent) {
		switch e.keyCode {
			case Keyboard.A, Keyboard.D, Keyboard.W, Keyboard.S:
				keys.set(e.keyCode, false);
		}
	}

	override function onUpdate(dt:Float) {
		super.onUpdate(dt);
		var speed = 50;
		if (isKeyDown(Keyboard.A)) {
			quad.x -= speed * dt;
		} else if (isKeyDown(Keyboard.D)) {
			quad.x += speed * dt;
		}
		if (isKeyDown(Keyboard.W)) {
			quad.y -= speed * dt;
		} else if (isKeyDown(Keyboard.S)) {
			quad.y += speed * dt;
		}
	}

	public function isKeyDown(keyCode:Int):Bool {
		return keys.get(keyCode);
	}
}
